﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
//using System.Windows.Controls;
//using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace TestIText
{
    public partial class MainPage : System.Windows.Controls.UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        Stream certificateStream;
        Stream pdfFileStream;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            openFileAndRunPDFProcess((resultFile) =>
            {
                // step 1: creation of a document-object
                Document document = new Document();
                try
                {
                    // step 2:
                    // we create a writer
                    PdfWriter.GetInstance(
                        // that listens to the document
                            document,
                        // and directs a PDF-stream to a file
                            resultFile);
                    // step 3: we open the document
                    document.Open();
                    // step 4: we add a paragraph to the document
                    Font font = new Font(Font.COURIER, 10, Font.BOLD);
                    Phrase p;
                    font.Color  = new iTextSharp.text.Color(0xFF, 0xFF, 0xFF);
                    Chunk fox = new Chunk("quick brown fox", font);
                    fox.SetBackground(new iTextSharp.text.Color(0xa5, 0x2a, 0x2a));
                    p = new Phrase();
                    p.Add(fox);
                    p.Add(" jumps over ");
                    Chunk dog = new Chunk("the lazy dog", new Font(Font.TIMES_ROMAN,
                            14, Font.ITALIC));
                    dog.SetBackground(new iTextSharp.text.Color(0xFF, 0x00, 0x00), 10f, -30f, 20f, -10f);
                    p.Add(dog);
                    document.Add(p);
                }
                catch (DocumentException de)
                {
                    Debug.WriteLine("Doc Error: " + de.Message);
                }
                catch (IOException ioe)
                {
                    Debug.WriteLine("IO Error: " + ioe.Message);
                }

                // step 5: we close the document
                document.Close();
            });
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            openFileAndRunPDFProcess((resultFile) =>
            {
                // step 1: creation of a document-object
                Document document = new Document(PageSize.A8.Rotate());
                try
                {
                    // step 2:
                    // we create a writer
                    var writer = PdfWriter.GetInstance(
                        // that listens to the document
                            document,
                        // and directs a PDF-stream to a file
                            resultFile);
                    // step 3: we open the document
                    document.Open();
                    // step 4: we add a paragraph to the document
                    String text = "Quick brown fox jumps over the lazy dog.";
                    var paragraph = new iTextSharp.text.Paragraph(text);
                    paragraph.Alignment = Element.ALIGN_JUSTIFIED;
                    document.Add(paragraph);
                    document.NewPage();
                    writer.SpaceCharRatio = PdfWriter.NO_SPACE_CHAR_RATIO;
                    document.Add(paragraph);
                }
                catch (DocumentException de)
                {
                    Debug.WriteLine("Doc Error: " + de.Message);
                }
                catch (IOException ioe)
                {
                    Debug.WriteLine("IO Error: " + ioe.Message);
                }

                // step 5: we close the document
                document.Close();
            });
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            openFileAndRunPDFProcess((resultFile) =>
            {
                // step 1: creation of a document-object
                Document document = new Document(PageSize.A8.Rotate());
                try
                {
                    // step 2:
                    // we create a writer
                    var writer = PdfWriter.GetInstance(
                        // that listens to the document
                            document,
                        // and directs a PDF-stream to a file
                            resultFile);
                    // step 3: we open the document
                    document.Open();

                    // step 4: we add a paragraph to the document
                    Phrase phrase = new Phrase("Quick brown fox jumps over");
                    document.Add(phrase);
                    List list1 = new List(List.ORDERED, 20);
                    list1.Add(new ListItem("the lazy dog"));
                    list1.Add(new ListItem("the lazy cat"));
                    list1.Add(new ListItem("the fence"));
                    document.Add(list1);
                    document.Add(Chunk.NEWLINE);
                    document.Add(phrase);
                    List list2 = new List(List.UNORDERED, 10);
                    list2.Add("the lazy dog");
                    list2.Add("the lazy cat");
                    list2.Add("the fence");
                    document.Add(list2);
                    document.Add(Chunk.NEWLINE);
                    document.Add(phrase);
                    List list3 = new List(List.ORDERED, List.ALPHABETICAL, 20);
                    list3.Add(new ListItem("the lazy dog"));
                    list3.Add(new ListItem("the lazy cat"));
                    list3.Add(new ListItem("the fence"));
                    document.Add(list3);
                    document.Add(Chunk.NEWLINE);
                    document.Add(phrase);
                    List list4 = new List(List.UNORDERED, 30);
                    list4.SetListSymbol("----->");
                    list4.IndentationLeft = 10f;
                    list4.Add("the lazy dog");
                    list4.Add("the lazy cat");
                    list4.Add("the fence");
                    document.Add(list4);
                    document.Add(Chunk.NEWLINE);
                    document.Add(phrase);
                    List list5 = new List(List.ORDERED, 20);
                    list5.First = 11;
                    list5.Add(new ListItem("the lazy dog"));
                    list5.Add(new ListItem("the lazy cat"));
                    list5.Add(new ListItem("the fence"));
                    document.Add(list5);
                    document.Add(Chunk.NEWLINE);
                    List list = new List(List.UNORDERED, 10);
                    list.ListSymbol = new Chunk('*');
                    list.Add("Quick brown fox jumps over");
                    list.Add(list1);
                    list.Add("Quick brown fox jumps over");
                    list.Add(list3);
                    list.Add("Quick brown fox jumps over");
                    list.Add(list5);
                    document.Add(list);
                }
                catch (DocumentException de)
                {
                    Debug.WriteLine("Doc Error: " + de.Message);
                }
                catch (IOException ioe)
                {
                    Debug.WriteLine("IO Error: " + ioe.Message);
                }

                // step 5: we close the document
                document.Close();
            });
        }

        private void buttonCreateTestPdf_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            openFileAndRunPDFProcess((resultFile)=> {

                    Document document = new Document(PageSize.A4);
                    PdfWriter writer = PdfWriter.GetInstance(document, resultFile);
                    document.Open();
                    document.Add(new iTextSharp.text.Paragraph("Screenshot of the Drawing:"));
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new WriteableBitmap(canvasDrawing, null));
                    image.ScalePercent(50);
                    document.Add(image);

                    document.Close();
                    writer.Close();
            });
        }

        private void openFileAndRunPDFProcess(Action<Stream> pdfCreateAction)
        {
            var saveFileDialog = new System.Windows.Controls.SaveFileDialog();
            saveFileDialog.Filter = "(*.pdf) | *.pdf";

            bool? dialogResult = saveFileDialog.ShowDialog();

            if (dialogResult.HasValue && dialogResult.Value)
            {
                using (Stream resultFile = saveFileDialog.OpenFile())
                {

                    try
                    {
                        pdfCreateAction(resultFile);

                    }
                    catch (Exception ex)
                    {

                        throw;
                    }
                }
            }
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            openFileAndRunPDFProcess((resultFile) =>
            {
                // step 1: creation of a document-object
                Document document = new Document(PageSize.LETTER.Rotate() );
                try
                {
                    // step 2:
                    // we create a writer
                    var writer = PdfWriter.GetInstance(
                        // that listens to the document
                            document,
                        // and directs a PDF-stream to a file
                            resultFile);
                    // step 3: we open the document
                    document.Open();

                    // step 4: we add a paragraph to the document
                    iTextSharp.text.Paragraph p;
                    Chunk chunk;
                    p = new iTextSharp.text.Paragraph();
                    chunk = new Chunk("Quick brown fox");
                    chunk.SetSkew(15f, -30f);
                    p.Add(chunk);
                    chunk = new Chunk(" jumps over ");
                    chunk.SetSkew(15f, 15f);
                    p.Add(chunk);
                    chunk = new Chunk("the lazy dog.");
                    chunk.SetSkew(-30f, 15f);
                    p.Add(chunk);
                    document.Add(p);
                    p = new Paragraph();
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    p = new Paragraph();
                    chunk = new Chunk("Quick brown fox");
                    chunk.SetSkew(45f, 0f);
                    p.Add(chunk);
                    chunk = new Chunk(" jumps over ");
                    p.Add(chunk);
                    chunk = new Chunk("the lazy dog.");
                    chunk.SetSkew(-45f, 0f);
                    p.Add(chunk);
                    document.Add(p);
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    p = new Paragraph();
                    chunk = new Chunk("Quick brown fox");
                    chunk.SetSkew(0f, 25f);
                    p.Add(chunk);
                    chunk = new Chunk(" jumps over ");
                    p.Add(chunk);
                    chunk = new Chunk("the lazy dog.");
                    chunk.SetSkew(0f, -25f);
                    p.Add(chunk);
                    document.Add(p);
                }
                catch (DocumentException de)
                {
                    Debug.WriteLine("Doc Error: " + de.Message);
                }
                catch (IOException ioe)
                {
                    Debug.WriteLine("IO Error: " + ioe.Message);
                }

                // step 5: we close the document
                document.Close();
            });

        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            openFileAndRunPDFProcess((resultFile) =>
            {
                // step 1: creation of a document-object
                Document document = new Document();
                try
                {
                    // step 2:
                    // we create a writer
                    var writer = PdfWriter.GetInstance(
                        // that listens to the document
                            document,
                        // and directs a PDF-stream to a file
                            resultFile);
                    // step 3: we open the document
                    document.Open();

                    // step 4

                    BaseFont bf1 = BaseFont.CreateFontFromSLResource(
                                        "Resources;component/resources/fonts/abserif4_5.ttf", "",
                                        BaseFont.NOT_EMBEDDED);
                    Font font1 = new Font(bf1, 12);
                    document
                            .Add(new Paragraph(
                                    "abserif4_5\n0123456789\nabcdefghijklmnopqrstuvwxyz\nABCDEFGHIJKLMNOPQRSTUVWXZ",
                                    font1));
                    
                    // Adding in code from Font metrics
                    AddFontMetricsToDoc(document, bf1, font1);

                    document
                            .Add(new Paragraph(" \n"));

                    BaseFont bf2 = BaseFont.CreateFontFromSLResource("Resources;component/resources/fonts/esl_gothic_shavian.otf", BaseFont.IDENTITY_H,
                            BaseFont.NOT_EMBEDDED);
                    Font font2 = new Font(bf2, 12);
                    document
                            .Add(new Paragraph(
                                    "esl_gothic_shavian\n0123456789\nabcdefghijklmnopqrstuvwxyz\nABCDEFGHIJKLMNOPQRSTUVWXZ",
                                    font2));
                    AddFontMetricsToDoc(document, bf2, font2);
                    document
                            .Add(new Paragraph(" \n"));

                    BaseFont bf3 = BaseFont.CreateFontFromSLResource("TestIText;component/resources/fonts/cmr10.afm", "",
                            BaseFont.NOT_EMBEDDED);
                    Font font3 = new Font(bf3, 12);
                    document
                            .Add(new Paragraph(
                                    "cmr10\n0123456789\nabcdefghijklmnopqrstuvwxyz\nABCDEFGHIJKLMNOPQRSTUVWXZ",
                                    font3));
                    AddFontMetricsToDoc(document, bf3, font3);
                    document
                            .Add(new Paragraph(" \n"));

                    BaseFont bf4 = BaseFont.CreateFontFromSLResource("TestIText;component/resources/fonts/cmr10.pfb", "",
                            BaseFont.NOT_EMBEDDED);
                    Font font4 = new Font(bf4, 12);
                    document
                            .Add(new Paragraph(
                                    "cmr10.pfb\n0123456789\nabcdefghijklmnopqrstuvwxyz\nABCDEFGHIJKLMNOPQRSTUVWXZ",
                                    font4));
                    AddFontMetricsToDoc(document, bf4, font4);
                    document
                            .Add(new Paragraph(" \n"));
                }
                catch (DocumentException de)
                {
                    Debug.WriteLine("Doc Error: " + de.Message);
                }
                catch (IOException ioe)
                {
                    Debug.WriteLine("IO Error: " + ioe.Message);
                }

                // step 5: we close the document
                document.Close();
            });

        }

        private static void AddFontMetricsToDoc(Document document, BaseFont bf1, Font font1)
        {
            String numbers = "0123456789";
            document.Add(new Paragraph("width: " + bf1.GetWidth(numbers)
              + " (" + bf1.GetWidthPoint(numbers, 12) + "pt)", font1));
            document.Add(new Paragraph("ascent: " + bf1.GetAscent(numbers)
              + "; descent: " + bf1.GetDescent(numbers)
              + "; height: " + (bf1.GetAscentPoint(numbers, 12)
                - bf1.GetDescentPoint(numbers, 12) + "pt"), font1));
        }

        private void button6_Click(object sender, RoutedEventArgs e)
        {
            openFileAndRunPDFProcess((resultFile) =>
            {
                // step 1: creation of a document-object
                Document document = new Document(PageSize.A4);
                try
                {
                    // step 2:
                    // we create a writer
                    var writer = PdfWriter.GetInstance(
                        // that listens to the document
                            document,
                        // and directs a PDF-stream to a file
                            resultFile);
                    // step 3: we open the document
                    document.Open();

                    // step 4: we add a table to the document
                    PdfContentByte cb = writer.DirectContent;
                    Image caesar = Image.GetInstance(@"resources\caesar.jpg");
                    cb.AddImage(caesar, 100, 0, 0, 100, 260, 595);
                    PdfTemplate t = cb.CreateTemplate(600, 800);
                    t.SetGrayFill(0.75f);
                    t.MoveTo(310, 112);
                    t.LineTo(280, 60);
                    t.LineTo(340, 60);
                    t.ClosePath();
                    t.MoveTo(310, 790);
                    t.LineTo(310, 710);
                    t.MoveTo(310, 580);
                    t.LineTo(310, 122);
                    t.FillStroke();
                    cb.AddTemplate(t, 0, 0);

                    //var sb = new System.Text.StringBuilder(1024);
                    //BufferedReader reader = new BufferedReader(new FileReader(
                    //        "resources/in_action/chapter07/caesar.txt"));
                    //int c;
                    var sb = new System.Text.StringBuilder();
                    using (var fs = Application.GetResourceStream(new Uri( @"TestIText;component/resources/caesar.txt", UriKind.Relative)).Stream)
                    {
                        using (var sr = new System.IO.StreamReader(fs))
                            sb.Append(sr.ReadToEnd());
                    }

                    ColumnText ct = new ColumnText(cb);
                    ct.SetText(new Phrase(sb.ToString()));
                    ct.Alignment = (Element.ALIGN_JUSTIFIED);

                    object[] left = new object[2];
                    left[0] = new [] { 70f, 790f, 70f, 60f };
                    left[1] = new[] { 320f, 790f, 320f, 700f, 380f, 700f, 380f, 590f, 320f, 590f, 320f,
							106f, 350f, 60f };
                    object[] right = new object[2];
                    right[0] = new [] { 300f, 790f, 300f, 700f, 240f, 700f, 240f, 590f, 300f, 590f, 300f,
							106f, 270f, 60f };
                    right[1] = new [] {  550f, 790f, 550f, 60f };
                    int status = ColumnText.START_COLUMN;
                    int column = 0;
                    while (ColumnText.HasMoreText(status))
                    {
                        if (column > 1)
                        {
                            column = 0;
                            document.NewPage();
                            cb.AddTemplate(t, 0, 0);
                            cb.AddImage(caesar, 100, 0, 0, 100, 260, 595);
                        }
                        ct.SetColumns((float[])left[column], (float[])right[column]);
                        ct.YLine =790;
                        status = ct.Go();
                        column++;
                    }
                }
                catch (DocumentException de)
                {
                    Debug.WriteLine("Doc Error: " + de.Message);
                }
                catch (IOException ioe)
                {
                    Debug.WriteLine("IO Error: " + ioe.Message);
                }

                // step 5: we close the document
                document.Close();
            });

        }

        /*
         openFileAndRunPDFProcess((resultFile) =>
                    {
                        // step 1: creation of a document-object
                        Document document = new Document(PageSize.A8.rotate());
                        try
                        {
                            // step 2:
                            // we create a writer
                            var writer = PdfWriter.GetInstance(
                                // that listens to the document
                                    document,
                                // and directs a PDF-stream to a file
                                    resultFile);
                            // step 3: we open the document
                            document.Open();

                            // step 4: 
                        }
                        catch (DocumentException de)
                        {
                            Debug.WriteLine("Doc Error: " + de.Message);
                        }
                        catch (IOException ioe)
                        {
                            Debug.WriteLine("IO Error: " + ioe.Message);
                        }

                        // step 5: we close the document
                        document.Close();
                    });
         */

    }
}
